package com.qilu.pe.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qilu.pe.R;
import com.qilu.pe.base.Base2Activity;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.dao.bean.Patient;
import com.qilu.pe.dao.bean.Pdf;
import com.qilu.pe.dao.bean.ReportDetail;
import com.qilu.pe.dao.bean.Test;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.AlertUtil;
import com.qilu.pe.support.util.Logg;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.ToastUtils;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 报告详情
public class ReportDetailActivity extends Base2Activity {
    private RecyclerView rcv_sample, rcv_test_item;// 样本列表，检测项目列表
    private TextView tv_name, tv_out_order_name, tv_sex_age, tv_phone;
    private TextView tv_order_no, tv_pay_date, tv_place_date, tv_note_content;
    private LinearLayout ll_1, ll_2, ll_3;// 申请专家解读,AI解读,查看专家解读
    private RelativeLayout rl_launch_wx_app, rl_pdf_preview;

    //样本和指标项
    private SampleListAdapter adapter;
    private List<ReportDetail.Report> sampleList = new ArrayList<>();

    // 检测项目
    private TestItemAdapter itemAdapter;
    private List<Test> testList = new ArrayList<>();

    private List<Pdf> pdfList = new ArrayList<>();

    private String order_id;// 传过来的

    private ReportDetail detail;// 请求得到的报告详情

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_report_detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv_name = findViewById(R.id.tv_name);
        tv_out_order_name = findViewById(R.id.tv_out_order_name);
        tv_sex_age = findViewById(R.id.tv_sex_age);
        tv_phone = findViewById(R.id.tv_phone);
        tv_order_no = findViewById(R.id.tv_order_no);
        tv_pay_date = findViewById(R.id.tv_pay_date);
        tv_place_date = findViewById(R.id.tv_place_date);
        tv_note_content = findViewById(R.id.tv_note_content);
        rcv_sample = findViewById(R.id.rcv_sample);
        rcv_test_item = findViewById(R.id.rcv_test_item);
        ll_1 = findViewById(R.id.ll_1);
        ll_2 = findViewById(R.id.ll_2);
        ll_3 = findViewById(R.id.ll_3);
        rl_launch_wx_app = findViewById(R.id.rl_launch_wx_app);
        rl_pdf_preview = findViewById(R.id.rl_pdf_preview);

        setNavigationIcon(R.mipmap.ic_left_arrow);

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            order_id = bundle.getString("order_id");
        }

        LinearLayoutManager manager = new LinearLayoutManager(this);
        adapter = new SampleListAdapter(this);
        rcv_sample.setLayoutManager(manager);
        rcv_sample.setAdapter(adapter);

        itemAdapter = new TestItemAdapter(this);
        LinearLayoutManager manager1 = new LinearLayoutManager(this);
        itemAdapter = new TestItemAdapter(this);
        rcv_test_item.setLayoutManager(manager1);
        rcv_test_item.setAdapter(itemAdapter);

        setHeadTitle("报告详情");

        hideProgress();
        reqReportDetail();
        showProgress();

        setListeners();
        alert = new AlertDialog.Builder(this, R.style.Dialog_FS).create();
    }

    private void setListeners() {
        setOnClickListener(tv_name, ll_1, ll_2, ll_3, rl_launch_wx_app, rl_pdf_preview);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == rl_launch_wx_app) {
            launchWxApp();
        }
        if (v == rl_pdf_preview) {
            hideProgress();
            reqPdfList();
            showProgress();
        }
        if (v == tv_name) {
            if (null != detail && null != detail.getUser()) {
                Bundle bundle = new Bundle();
                Patient patient = new Patient();
                ReportDetail.User user = detail.getUser();
                patient.setId(user.getId());
                patient.setName(user.getName());
                patient.setSex(user.getSex());
                patient.setBirth(user.getBirth());
                patient.setPhone(user.getPhone());
                patient.setPicture("");
                bundle.putSerializable("patient", patient);
                startActivity(PatientDetailActivity.class, bundle);
            } else {
                ToastUtils.showShort("数据加载中,请稍候");
            }
        }
        if (v == ll_1) {// 申请专家解读
            if (null != detail && null != detail.getUser()) {
                Bundle bundle = new Bundle();
                bundle.putString("orderId", order_id);
                bundle.putString("sid", detail.getUser().getId());
                startActivity(ConfirmExpertExplainActivity.class, bundle);
            } else {
                ToastUtils.showShort("数据加载中,请稍后");
            }
        }
        if (v == ll_2) {
            startActivity(AiExplainActivity.class);
        }
        if (v == ll_3) {
            startActivity(ExplainDetailActivity.class);
        }
    }

    // 设置报告详情数据
    private void setData2View() {

        ReportDetail.User user = detail.getUser();
        if (null != user) {
            tv_name.setText(user.getName());
            tv_out_order_name.setText("出单人:" + user.getDoctor());
            String sex = TextUtils.equals("0", user.getSex()) ? "男" : "女";
            tv_sex_age.setText("性别:" + sex + "    年龄:" + user.getBirth());
            tv_phone.setText("电话:" + user.getPhone());
        }

        ReportDetail.Order order = detail.getOrder();
        if (null != order) {
            List<String> itemNameList = order.getName();
            itemAdapter.setDataList(itemNameList);

            tv_order_no.setText(order.getOrder_num());
            tv_pay_date.setText(order.getPay_time());
            tv_place_date.setText(order.getTime());
            tv_note_content.setText(order.getRemark());
        }

        sampleList = detail.getReport();
        adapter.setDataList(sampleList);
    }

    private AlertDialog alert;// 弹窗
    private View alert_view;

    public void showDialog() {// 弹窗
        alert.show();
        alert_view = View.inflate(this, R.layout.layout_alert_report_pdf_list, null);

        TextView tv_close = alert_view.findViewById(R.id.tv_close);
        RecyclerView rcv_pdf_list = alert_view.findViewById(R.id.rcv_pdf_list);
        LinearLayoutManager manager = new LinearLayoutManager(ReportDetailActivity.this);
        PdfListAdapter adapter = new PdfListAdapter(this);
        rcv_pdf_list.setLayoutManager(manager);
        rcv_pdf_list.setAdapter(adapter);
        adapter.setDataList(pdfList);

        tv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.dismiss();
            }
        });

        AlertUtil.setAlertCenterStyle(alert.getWindow(), alert_view, this);
    }

    // 请求pdf列表
    private Disposable reqPdfList() {
        return APIRetrofit.getDefault().reqPdfList(Global.HEADER, order_id)
                .compose(RxUtil.<BaseResult2<List<Pdf>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Pdf>>>() {
                    @Override
                    public void accept(BaseResult2<List<Pdf>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            pdfList = listBaseResult2.getData();
                            showDialog();
                        } else {

                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 请求报告详情
    private Disposable reqReportDetail() {
        return APIRetrofit.getDefault().reqReportDetail(Global.HEADER, order_id)
                .compose(RxUtil.<BaseResult2<List<ReportDetail>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<ReportDetail>>>() {
                    @Override
                    public void accept(BaseResult2<List<ReportDetail>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            if (!isDataEmpty(listBaseResult2.getData())) {
                                detail = listBaseResult2.getData().get(0);
                                if (null != detail) {
                                    setData2View();
                                } else {
                                    Logg.i("reqReportDetail().detai = null");
                                }
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 打开微信小程序
    private void launchWxApp() {
        IWXAPI api = WXAPIFactory.createWXAPI(this, Config.WX_APP_ID);
        WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
        req.userName = "gh_8ffd72b8d002"; // 填小程序原始id
        req.path = "pages/reports/detail?id=" + order_id; //拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
        req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
        api.sendReq(req);
    }

    private class SampleListAdapter extends ListBaseAdapter<ReportDetail.Report> {

        public SampleListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_sample_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_name = holder.getView(R.id.tv_name);
            RecyclerView rcv_indicator_standard = holder.getView(R.id.rcv_indicator_standard);

            ReportDetail.Report sample = mDataList.get(position);// 样本对象，里面包含指标检测值列表
            tv_name.setText("样本" + sample.getTest_code());

            LinearLayoutManager manager = new LinearLayoutManager(ReportDetailActivity.this);
            IndicatorStandardAdapter adapter = new IndicatorStandardAdapter(ReportDetailActivity.this);
            rcv_indicator_standard.setLayoutManager(manager);
            rcv_indicator_standard.setAdapter(adapter);

            List<ReportDetail.Report.Info> standardList = sample.getInfo();// 指标检测列表
            adapter.setDataList(standardList);
        }
    }

    public class IndicatorStandardAdapter extends ListBaseAdapter<ReportDetail.Report.Info> {
        public IndicatorStandardAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_indicator_standard_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_item_val = holder.getView(R.id.tv_item_val);// 指标项
            TextView tv_code_val = holder.getView(R.id.tv_code_val);// 代码
            TextView tv_test_val = holder.getView(R.id.tv_test_val);// 检测值
            TextView tv_reference_val = holder.getView(R.id.tv_reference_val);// 参考值

            ReportDetail.Report.Info info = mDataList.get(position);
            tv_item_val.setText(info.getHosprptitemname());
            tv_code_val.setText(info.getHosprptitemcode());
            tv_test_val.setText(info.getResult_str());
            tv_reference_val.setText(info.getResult_ref());
        }
    }

    private class TestItemAdapter extends ListBaseAdapter<String> {

        public TestItemAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_test_item_list_2;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_name = holder.getView(R.id.tv_name);

            String name = mDataList.get(position);
            tv_name.setText(name);
        }
    }

    private class PdfListAdapter extends ListBaseAdapter<Pdf> {

        public PdfListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_pdf_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_name = holder.getView(R.id.tv_name);
            TextView tv_preview = holder.getView(R.id.tv_preview);

            final Pdf pdf = mDataList.get(position);

            final String name = pdf.getReport_id();
            final String path = pdf.getPath();
            tv_name.setText(name);

            // 预览pdf
            tv_preview.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (TextUtils.isEmpty(path)) {// pdf路径为空
                        ToastUtils.showShort("未找到pdf报告,请联系工作人员!");
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putString("title", name);
                    bundle.putString("url", Config.URL_IMG + path);
                    startActivity(PdfPreviewActivity.class, bundle);
                }
            });
        }
    }
}